<?php
namespace control;
/*
*商机类
*/

class opportunityClass extends adIndexClass
{
    private const title = '商机';
    private const page = 'opportunity';
    private const table = 'opportunity';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'logSearch':
                $tr = [
                    'time'          => [
                        'name'  => L('opportunity.logSearch.time'),
                        'width' => 400,
                        'sort' => 1,
                    ],
                    'staffName' => [
                        'name'  => L('opportunity.logSearch.staffName'),
                        'width' => 400,
                    ],
                    'type'  => [
                        'name'  => L('opportunity.logSearch.type'),
                        'width' => 400,
                        'sort' => 1,
                    ],
                    'text'         => [
                        'name'  => L('opportunity.logSearch.text'),
                        'width' => 400,
                    ]
                ];
                break;
            case 'clientOptSearch':
                $tr = [
                    'name'          => [
                        'name'  => L('opportunity.edit.name'),
                        'width' => 200,
                    ],
                    'exSaleMoney' => [
                        'name'  => L('opportunity.edit.exSaleMoney')."（".static::$unit."）",
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'exSignDate'  => [
                        'name'  => L('opportunity.edit.exSignDate'),
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'stage'         => [
                        'name'  => L('opportunity.edit.stage'),
                        'width' => 180,
                    ],
                    'possibility'          => [
                        'name'  => L('opportunity.edit.possibility'),
                        'width' => 180,
                    ],
                    'manager'          => [
                        'name'  => L('opportunity.edit.manager'),
                        'width' => 180,
                    ],
                    'text'          => [
                        'name'  => L('opportunity.cooperationSearch.record'),
                        'width' => 250,
                    ],
                    'time'          => [
                        'name'  => L('opportunity.cooperationSearch.followTime'),
                        'width' => 200,
                    ],
                ];
                break;
            case 'cooperationSearch':
            case 'allClueSearch':
                $tr = [
                    'name'          => [
                        'name'  => L('opportunity.cooperationSearch.name'),
                        'width' => 200,
                    ],
                    'companyName' => [
                        'name'  => L('opportunity.cooperationSearch.companyName'),
                        'width' => 180,
                    ],
                    'exSaleMoney'  => [
                        'name'  => L('opportunity.cooperationSearch.exSaleMoney')."（".static::$unit."）",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'exSignDate'         => [
                        'name'  => L('opportunity.cooperationSearch.exSignDate'),
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'stage'          => [
                        'name'  => L('opportunity.cooperationSearch.stage'),
                        'width' => 150,
                    ],
                    'possibility'          => [
                        'name'  => L('opportunity.cooperationSearch.possibility'),
                        'width' => 150,
                    ],
                    'manager'          => [
                        'name'  => L('opportunity.cooperationSearch.manager'),
                        'width' => 200,
                    ],
                    'text'          => [
                        'name'  => L('opportunity.cooperationSearch.record'),
                        'width' => 200,
                    ],
                    'time'          => [
                        'name'  => L('opportunity.cooperationSearch.followTime'),
                        'width' => 150,
                    ],
                ];
                break;
            default:
                $tr = [
                    'name'          => [
                        'name'  => L('opportunity.cooperationSearch.name'),
                        'width' => 200,
                    ],
                    'companyName' => [
                        'name'  => L('opportunity.cooperationSearch.companyName'),
                        'width' => 150,
                    ],
                    'exSaleMoney'  => [
                        'name'  => L('opportunity.cooperationSearch.exSaleMoney')."（".static::$unit."）",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'exSignDate'         => [
                        'name'  => L('opportunity.cooperationSearch.exSignDate'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'stage'          => [
                        'name'  => L('opportunity.cooperationSearch.stage'),
                        'width' => 200,
                    ],
                    'possibility'          => [
                        'name'  => L('opportunity.cooperationSearch.possibility'),
                        'width' => 200,
                    ],
                    'text'          => [
                        'name'  => L('opportunity.cooperationSearch.record'),
                        'width' => 200,
                    ],
                    'time'          => [
                        'name'  => L('opportunity.cooperationSearch.followTime'),
                        'width' => 150,
                    ],
                ];
        }
        return $tr;
    }

    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow): string
    {
        $array = [
            [
                [
                    L('opportunity.homeForm.name') => text(array("name" => "name")),
                    L('opportunity.homeForm.companyName')   => text(array("name" => "companyName")),
                    L('opportunity.homeForm.stage') => select(array('name' => 'stage', 'option' => explode('，', para('stageOption')))),
                ],
                [
                    L('opportunity.homeForm.possibility') => select(array('name' => 'possibility', 'option' => explode('，', para('possibilityOption')))),
                    L('opportunity.detail.time') => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ];
        if ($workFlow == '我协作的') {
            $array[0][1][L('opportunity.homeForm.manager')] = selectMultiple(array('table' => 'staff', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'manager', 'class' => 'width200'));
        } elseif ($workFlow == '全部商机') {
            $array[0][1][L('opportunity.homeForm.manager')] = selectMultiple(array('table' => 'staff', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'manager', 'class' => 'width200'));
        }
        return $this->tableShow($array,1);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('我的商机');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 查询条件
     *
     * @return string
     */
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>" . L('opportunity.home.new') . "</span>\n
                        <span onclick=\"layer('" . self::page . "','transfer',{})\" class='spanButton'>" . L('opportunity.cooperationSearch.transfer') . "</span>\n";

        }
        //导入
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('opportunity.home.del')."</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*社保数据-列表页-查询结果*/
    public function homeSearch()
    {
        //全等查询数组
        $equal = array(
            'a.coid'=>self::$coid,
            "a.manager" => self::$stid,//员工
            'a.possibility' => $this->post('possibility'),
            'a.stage' => $this->post('stage'),
        );
        $like = array(
            "a.name" => $this->post('name'),//标题
            "b.companyName" => $this->post('companyName'),
        );
        $and = "";
        if ($this->post('time')) {
            $timeArr = explode(' ~ ', $this->post('time'));
            $and .= " and date(a.time) >='{$timeArr[0]}' and date(a.time) <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(
                'time'=>'a.time'
            ),
        ));
        //获取查询结果
        $where = search(array("=" => $equal, 'like' => $like)) . $and;
        $page = $this->page(array(
            "table" => self::table . " as a join kehu as b on a.khid = b.khid",
            'field' => 'a.*,b.companyName',
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => L('opportunity.home.edit'), "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
                "detail" => array("title" => L('opportunity.cooperationSearch.detail'), "click" => "newIframe('" . L('opportunity.cooperationSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            $follow = query('follow', " targetId = '$array[id]' order by time desc");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "text":
                    case "time":
                        $row[] = $follow[$key];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table . " as a join kehu as b on a.khid = b.khid",
            'single' => $where,
            'field'  => "ifnull(sum(a.exSaleMoney),0) as money",
        ]);
        $total    = [
            'exSaleMoney'      => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function cooperationOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('我协作的');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 我协作的
     *
     */
    public function cooperation(): bool|string
    {
        $html = $this->cooperationOptions(false);
        $button = "";
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function cooperationSearch(): bool|string
    {
        //全等查询数组
        $equal = array(
            'a.coid'=>self::$coid,
            "a.manager" => $this->post('manager'),//员工
            'a.possibility' => $this->post('possibility'),
            'a.stage' => $this->post('stage'),
        );
        $like = array(
            "a.name" => $this->post('name'),//标题
            "b.companyName" => $this->post('companyName'),
            "a.collaborator" => self::$stid
        );
        $and = "";
        if ($this->post('time')) {
            $timeArr = explode(' ~ ', $this->post('time'));
            $and .= " and date(a.time) >='{$timeArr[0]}' and date(a.time) <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(
                'time'=>'a.time'
            ),
        ));
        //获取查询结果
        $where = search(array("=" => $equal, 'like' => $like)) . $and;
        $page = $this->page(array(
            "table" => self::table . " as a join kehu as b on a.khid = b.khid",
            'field' => 'a.*,b.companyName',
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("cooperationForm", "copId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "copId", "value" => $array['id']),
                "detail" => array("title" => L('opportunity.cooperationSearch.detail'), "click" => "newIframe('" . L('opportunity.cooperationSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            $follow = query('follow', " targetId = '$array[id]' order by time desc");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "manager":
                        $row[] = self::findStaff($array['manager']);
                        break;
                    case "text":
                    case "time":
                        $row[] = $follow[$key];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table . " as a join kehu as b on a.khid = b.khid",
            'single' => $where,
            'field'  => "ifnull(sum(a.exSaleMoney),0) as money",
        ]);
        $total    = [
            'exSaleMoney'      => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='cooperationForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function allClueOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('全部商机');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    public function allClue(): bool|string
    {
        $html = $this->allClueOptions(false);
        //控件
        $button = "";
        if ($this->power('allOpportunity', "admin")) {
            $button .= "<span onclick=\"layer('" . self::page . "','transfer',{})\" class='spanButton'>" . L('opportunity.cooperationSearch.transfer') . "</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function allClueSearch()
    {
        //自己的，协作的，直接下级的
        //全等查询数组
        $equal = array(
            'a.coid'=>self::$coid,
            "a.manager" => $this->post('manager'),//员工
            'a.possibility' => $this->post('possibility'),
            'a.stage' => $this->post('stage'),
        );
        $like = array(

            "a.name" => $this->post('name'),//标题
            "b.companyName" => $this->post('companyName'),
        );
        $and = "";

        if ($this->power(self::page, "seeAll")) {
            //查看所有客户的权限
            $and .= " and 1=1";
        }elseif($this->power(self::page, "seeGroup")){
            //查看本组（直接下级）
            $and .= " and (a.collaborator like '%" . self::$stid . "%'  or a.manager = '" . self::$stid . "' or a.manager in (select stid from staff where manager = '" . self::$stid . "'))";
        }else{
            //查看自己
            $and .= " and (a.collaborator like '%" . self::$stid . "%'  or a.manager = '" . self::$stid . "')";
        }
        if ($this->post('time')) {
            $timeArr = explode(' ~ ', $this->post('time'));
            $and .= " and date(a.time) >='{$timeArr[0]}' and date(a.time) <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(
                'time'=>'a.time'
            ),
        ));
        //获取查询结果
        $where = search(array("=" => $equal, 'like' => $like)) . $and;
        $page = $this->page(array(
            "table" => self::table . " as a join kehu as b on a.khid = b.khid",
            'field' => 'a.*,b.companyName',
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("allClueForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => L('opportunity.cooperationSearch.detail'), "click" => "newIframe('" . L('opportunity.cooperationSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            $follow = query('follow', " targetId = '$array[id]' order by time desc");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "manager":
                        $row[] = self::findStaff($array['manager']);
                        break;
                    case "text":
                    case "time":
                        $row[] = $follow[$key];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table . " as a join kehu as b on a.khid = b.khid",
            'single' => $where,
            'field'  => "ifnull(sum(a.exSaleMoney),0) as money",
        ]);
        $total    = [
            'exSaleMoney'      => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='allClueForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 转交
     */
    public function transfer()
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . L('opportunity.transfer.manager')."：" => selectMultiple(array("title" => L('opportunity.transfer.choice'), 'option' => $this->staffOption(), 'name' => 'manager')),
            ),
            array(
                L('opportunity.transfer.collaborator')."：" => selectMultiple(array('table' => 'staff', 'multiple' => true, "title" => L('opportunity.transfer.choice'), 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'collaborator[]')),
            ),

        )
        ));
        //返回
        return $this->layer(array("title" => L('opportunity.transfer.transfer'), 'winFix' => true, "height" => 260, "html" => $html, 'formTwo' => 'listForm,allClueForm'));
    }

    /**
     * 获取转交给他人的选项
     * @return array
     */
    public function staffOption(): array
    {
        $option = [];
        $result = find(array('table' => 'staff', 'where' => "state in ('试用','转正')"));
        foreach ($result['array'] as $array) {
            $option[$array['stid']] = $array['name'];
        }
        return $option;
    }


    /**
     * 转交编辑
     */
    public function transferEdit()
    {
        $listId = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        $field = array(
            'manager' =>  $this->post('manager'),
            'collaborator' => $this->post('collaborator') && is_array($this->post('collaborator')) ? implode(',', array_unique($this->post('collaborator'))) : '',
        );
        if (!$this->power(self::page, 'edit') && !$this->power('allOpportunity', "admin")) {
            $json['warn'] = L('opportunity.transferEdit.power');
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = L('opportunity.transferEdit.noChoice');
        } elseif (empty($this->post('manager'))) {
            $json['warn'] = L('opportunity.transferEdit.manage');;
        } elseif (is_array($this->post('collaborator')) && in_array($field['manager'], $this->post('collaborator'))) {
            $json['warn'] = L('opportunity.transferEdit.collaboratorError');;
        } else {
            $x = 0;
            //查看范围
            $field['see'] = implode(',', array_unique(array_filter(array_merge([$field['manager']],explode(',', $field['collaborator'])))));
            $manager = query('staff', "stid = '$field[manager]'");
            foreach ($listId as $id) {
                $info = query(self::table, " id = '$id'");
                if ($info['manager'] != $field['manager'] && ($info['manager'] == self::$stid || $this->power('allOpportunity','admin'))) {
                    $warn = update(array(
                        'table' => self::table,
                        'field' => $field,
                        'where' => " id = '$id'"
                    ));
                    if ($warn == '更新成功') {
                        $x++;
                        $this->logWrite($id, '转交',str_replace(['{{staffName}}','{{name}}'], [$this->control['name'],$info['name']], L('opportunity.transferEdit.logWrite')) . $manager['name']);
                        $text = str_replace(['{{staffName}}','{{name}}','{{id}}'], [$this->control['name'],$info['name'],$id], L('opportunity.transferEdit.log')) . $manager['name'];
                        $this->logText(["type" => self::page, "text" => $text]);
                    }
                }else{
                    $text = str_replace(['{{staffName}}','{{name}}'], [$this->control['name'],$info['name']], L('opportunity.transferEdit.failLog'));
                    $this->logText(["type" => self::page, "text" => $text]);
                }
            }
            $json['warn'] = 2;
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('opportunity.transferEdit.warn'));
        }
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id')?:self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        $kehu = query('kehu',"khid = '".($this->post('khid')?:$info['khid'])."'");
        $all = find(array('table'=>'kehu_staff',"where"=>"khid = '{$kehu['khid']}' order by time asc"));
        //把客户基本信息中的常用联系人添加到跟进中
        $option['frequent']=$kehu['contactName'];
        foreach ($all['array'] as $val) {
            $option[$val['id']] = $val['name'];
        }
        $option = array_filter($option);
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('opportunity.edit.name')."：" => text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                    must . L('opportunity.edit.khid')."：" => clientClass::kehuSelect(array('change' => "getContacts",'value'=>$kehu['khid'])),
                ],
                [
                    L('opportunity.edit.contacts')."：" => "<div id='contacts' style='width: 100%;'>" . selectMultiple(["name" => "contacts[]", 'option' =>$option,'multiple' => true, 'title' => L('opportunity.edit.choice'), "value" => $info['contacts']]) . "</div>",
                    //L('opportunity.edit.products')."：" => selectMultiple(["name" => "products[]", 'table' => "material",'where'=>"state = '启用'", 'sqlId' => 'id', 'sqlField' => 'name', 'multiple' => true, 'title' => L('opportunity.edit.choice'), "value" => $info['products']]),
                ],
                [
                    must .L('opportunity.edit.exSaleMoney')."：" => text(["name" => "exSaleMoney", 'unit' =>  static::$unit , "value" => $info['exSaleMoney']]),
                    must .L('opportunity.edit.exSignDate')."：" => text(["name" => "exSignDate", 'laydate' => [], 'class' => 'text', "value" => $info['exSignDate']]),
                ],
                [
                    L('opportunity.edit.stage')."：" => select(["name" => "stage", 'class' => 'text', 'title' => L('opportunity.edit.stage'), 'option' => explode('，', para('stageOption')), "value" => $info['stage']]),
                    L('opportunity.edit.possibility')."：" => select(["name" => "possibility", 'class' => 'text', 'title' => L('opportunity.edit.possibility'), 'option' => explode('，', para('possibilityOption')), "value" => $info['possibility']]),
                ],
                [
                    L('opportunity.edit.obtainDate')."：" => text(["name" => "obtainDate", 'laydate' => [], 'class' => 'text', "value" => $info['obtainDate']]),
                    L('opportunity.edit.source')."：" => select(["name" => "source", 'class' => 'text', 'title' => L('opportunity.edit.source'), 'option' => explode('，', para('opportunityOption')), "value" => $info['source']]),
                ],
                [
                    L('opportunity.edit.reason')."：" => select(["name" => "reason", 'class' => 'text', 'title' => L('opportunity.edit.reason'), 'option' => explode('，', para('lostOpportunityOption')), "value" => $info['reason']]),
                    L('opportunity.edit.followTime')."：" => text(["name" => "followTime", 'laydate' => ['type' => 'datetime'], 'class' => 'text', "value" => $info['followTime']]),
                ],
                [
                    must . L('opportunity.edit.manager')."：" => selectMultiple(array('table' => 'staff', "title" => L('opportunity.edit.choice'), 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'manager', 'value' => $info['manager'] ?: self::$stid)),
                    L('opportunity.edit.collaborator')."：" => selectMultiple(array('table' => 'staff', 'where' => " stid !='$info[manager]'", 'multiple' => true, "title" => L('opportunity.edit.choice'), 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'collaborator[]', 'value' => $info['collaborator'])),
                ],
                [
                    L('opportunity.edit.text')."：" => textarea(["name" => "text", 'class' => 'textarea', "value" => $info['text']])
                ],
                [
                    L('opportunity.edit.file')."：" => fileUploadClass::addFileComponent($id, '商机', self::page, self::page . 'EditForm')
                ],
            ],
        ]);
        $html .= <<<efo
                    <script>
                     function getContacts(){
                         let khid = $("[name='khid']").val();
                         let val = $("[name='contacts[]']").val();
                         if (val){
                             val = val.join(',');
                         }
                         $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getContacts',{khid:khid,val:val},function(res) {
                            $("#contacts").empty().append(res.html);
                         },'json')
                     }
                    </script>
efo;
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 550, "html" => $html));
    }

    /**
     * 获取联系人
     */
    public function getContacts()
    {
        $khid = $this->post('khid');
        $value = $this->post('val');
        $kehu = query('kehu',"khid = '$khid'");
        $all = find(array('table'=>'kehu_staff',"where"=>"khid = '{$khid}' order by time asc"));
        //把客户基本信息中的常用联系人添加到跟进中
        $option['frequent']=$kehu['contactName'];
        foreach ($all['array'] as $val) {
            $option[$val['id']] = $val['name'];
        }
        $option = array_filter($option);
        $json['html'] = selectMultiple(["name" => "contacts[]", 'option' =>$option, 'multiple' => true, 'title' => '请选择', "value" => $value]);
        return json_encode($json, 320);
    }

    public function editEdit()
    {
        $fileIdArr = $this->post('fileId');
        $id = $this->post('id') ?: self::getId();
        $field = [
            'name' => $this->post('name'),
            'khid' => $this->post('khid'),
            'contacts' => $this->post('contacts') ? implode(',', $this->post('contacts')) : '',
            'products' => $this->post('products') ? implode(',', $this->post('products')) : '',
            'exSaleMoney' => $this->post('exSaleMoney'),
            'exSignDate' => $this->post('exSignDate'),
            'stage' => $this->post('stage'),
            'possibility' => $this->post('possibility'),
            'obtainDate' => $this->post('obtainDate'),
            'source' => $this->post('source'),
            'followTime' => $this->post('followTime'),
            'manager' => $this->post('manager'),
            'collaborator' => $this->post('collaborator') && is_array($this->post('collaborator')) ? implode(',', array_unique($this->post('collaborator'))) : '',
            'text' => $this->post('text'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'name' => L('opportunity.editEdit.name'),
            'khid' => L('opportunity.editEdit.khid'),
            'exSaleMoney' => L('opportunity.editEdit.exSaleMoney'),
            'exSignDate' => L('opportunity.editEdit.exSignDate'),
            'manager' => L('opportunity.editEdit.manager'),
        ];
        $rules = [
            'name' => 'required',
            'khid' => 'required',
            'exSaleMoney' => 'required|numeric',
            'exSignDate' => 'required',
            'manager' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('opportunity.editEdit.power');
        } elseif (is_array($this->post('collaborator')) && in_array($field['manager'], $this->post('collaborator'))) {
            $json['warn'] = L('opportunity.editEdit.collaborator');
        } else {
            //查看范围
            $field['see'] = implode(',', array_unique(array_merge(explode(',', $field['collaborator']), [$field['manager']])));

            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'coid'=>self::$coid,
                    'stid' => $this->control['stid'],
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                if (is_array($fileIdArr)) {
                    update([
                        'table' => 'file',
                        'field' => ['targetId' => $id],
                        'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"
                    ]);
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('opportunity.editEdit.log'));
                $this->logWrite($id, $type);
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('opportunity.detail.empty');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => L('opportunity.detail.detail'),
                'menu' => [
                    'edit' => L('opportunity.detail.info'),
                    'file' => array("name" => L('opportunity.detail.file'), "cla" => "file", "fun" => "opportunityFile"),
                    'follow' => array("name" => L('opportunity.detail.follow'), "cla" => "follow", "fun" => "opportunityRecord"),
                    'log' => L('opportunity.detail.log')
                ]
            );
            $button = [];
            if ($this->power(self::page, "edit") && self::$stid == $info['manager']) {
                //按钮
                $button[] = [
                    "name" => L('opportunity.detail.edit'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
                $button[] = [
                    "name" => L('opportunity.detail.newQuotation'),
                    "type" => "顶部页卡",
                    "title" => L('opportunity.detail.newQuotation'),
                    "url" => $this->root . 'control/adIndex.html?cla=quotations&fun=edit&opId=' . $info['id'],
                ];
                //按钮
                $button[] = [
                    "name" => L('opportunity.detail.transfer'),
                    "type" => "点击事件",
                    "title" => L('opportunity.detail.transfer'),
                    'fun' => "layer('" . self::page . "','transfer',{id:'" . $info['id'] . "'})",
                ];
            }
            //按钮
            $button[] = [
                "name" => L('opportunity.detail.clientDetail'),
                "type" => "顶部页卡",
                "title" => L('opportunity.detail.clientDetail'),
                "url" => $this->root . 'control/adIndex.html?cla=client&fun=detail&id=' . $info['khid'],
            ];
            if ($this->power(self::page, "del") and self::$stid == $info['manager']) {
                //按钮
                $button[] = [
                    "name" => L('opportunity.detail.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            $kehu = query('kehu', "khid = '$info[khid]'");
            //联系人
            $contacts = '';
            $contactId = explode(',', $info['contacts']);
            foreach ($contactId as $array) {
                if ($array =='frequent'){
                    $kehuStaff['name'] = $kehu['contactName'];
                }else{
                    $kehuStaff = query('kehu_staff',"id = '$array'");
                }
                $contacts .= clueClass::setBackGroundColorGray($kehuStaff['name']);
            }

            //产品
            $products = '';
            $result = find(array('table' => 'material', "where" => "id in ('" . implode("','", explode(',', $info['products'])) . "')"));
            foreach ($result['array'] as $array) {
                $products .= clueClass::setBackGroundColorGray($array['name']);
            }
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        L('opportunity.edit.name') => $info['name'],
                        L('opportunity.edit.khid') => $kehu['companyName'],
                        L('opportunity.edit.contacts') => $contacts,
                        L('opportunity.edit.products') => $products,
                    ),
                    array(
                        L('opportunity.edit.exSaleMoney') => $info['exSaleMoney'],
                        L('opportunity.edit.exSignDate') => $info['exSignDate'],
                    ),
                ),
                L('opportunity.detail.manageInfo') => array(
                    array(
                        L('opportunity.edit.stage') => $info['stage'],
                        L('opportunity.edit.possibility') => $info['possibility'],
                        L('opportunity.edit.obtainDate') => $info['obtainDate'],
                        L('opportunity.edit.reason') => $info['reason'],
                    ),
                    array(
                        L('opportunity.edit.source') => $info['source'],
                        L('opportunity.edit.followTime') => $info['followTime'],
                        L('opportunity.edit.manager') => self::findStaff($info['manager']),
                        L('opportunity.edit.collaborator') => clueClass::showMember($info['collaborator']),
                    ),
                    array(
                        L('opportunity.edit.text') => $info['text'],
                    )
                ),
                L('opportunity.edit.file') => array(
                    array(
                        fileUploadClass::showFile($info['id'], '商机')
                    ),
                ),
                L('opportunity.detail.sys') => array(
                    array(
                        L('opportunity.detail.stid') => self::findStaff($info['stid']) . hidden(array('name' => 'id', 'value' => $info['id'])),
                        L('opportunity.detail.time') => $info['time'],
                        L('opportunity.detail.updateTime') => $info['updateTime'],
                    ),
                )
            ));
            //生成页面
            $data['html'] .= <<<efo
<style>
.display-hidden{border: none}
.display-hidden:focus{border: 1px solid #d7d7d7;line-height: 16px;
    height: 16px;
    width: 200px;
    padding: 6px;
    border-radius: 4px;}
</style>
<script>
function setVal(value){
      let id = $("[name='id']").val();
     $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=setVal',{id:id,value:value},function(res) {
                if(res.warn !== 1){
                   warn(res.warn)
                }
            },'json')
}
</script>
efo;

            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 填写生日
     * @return bool|string
     */
    public function setVal()
    {
        $id = $this->post('id');
        $value = $this->post('value');
        $info = query(self::table, " id = '$id' ");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('opportunity.detail.power');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('opportunity.detail.empty');
        } else {
            $json['warn'] = update([
                'table' => self::table,
                'field' => [
                    'birthDay' => $value,
                ],
                'where' => " id = '$id' "
            ]);
            if ($json['warn'] == '更新成功') {
                $json['warn'] = 1;
                $this->logWrite($id, '更新');
            }
        }
        return json_encode($json, 320);
    }


    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = L('opportunity.downloadModel.power');
        } else {
            $exampleData[] = [];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '商机标题'=>$example[0],
                            '对应客户'=>$example[1],
                            '关联联系人'=>$example[2],
                            '预计销售金额'=>$example[3],
                            '预计签单日期'=>$example[4],
                            '销售阶段'=>$example[5],
                            '签单可能性'=>$example[6],
                            '输单原因'=>$example[7],
                            '商机获取日期'=>$example[8],
                            '商机来源'=>$example[9],
                            '下次跟进时间'=>$example[10],
                            '负责人'=>$example[11],
                            '负责人编号'=>$example[12],
                            '协作人'=>$example[13],
                            '协作人编号'=>$example[14],
                            '备注'=>$example[15],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }

            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('opportunity.downloadModel.log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }



    /*数据导入*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = L('opportunity.importData.power');
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $manager = query("staff", "orderNo = '$cell[负责人编号]'");
                    $partner = explode(',', $cell['协作人编号']);
                    $kehu = query('kehu',"companyName = '$cell[对应客户]'");
                    $collaborator = [];
                    foreach ($partner as $stid) {
                        $staff = query('staff', "stid = '$stid'");
                        $collaborator[] = $staff['stid'];
                    }
                    $contacts =  explode(',', $cell['关联联系人']);
                    $contactsId = [];
                    foreach ($contacts as $name){
                        $kehuStaff = query('kehu_staff',"name = '$name' and khid = '$kehu[khid]'");
                        $contactsId[] = $kehuStaff['id'];
                    }
                    $contactsId = array_unique(array_filter($contactsId));
                    $field = [
                        'id'=>suiji(),
                        'coid'=>self::$coid,
                        'name' => $cell['商机标题'],
                        'khid' => $kehu['khid'],
                        'contacts' =>implode(',',$contactsId),
                        'exSaleMoney' => $cell['预计销售金额'],
                        'exSignDate' => self::importDateFormat($cell['预计签单日期']),
                        'stage' => $cell['销售阶段'],
                        'possibility' => $cell['签单可能性'],
                        'reason' => $cell['输单原因'],
                        'obtainDate' => $cell['商机获取日期'],
                        'source' =>$cell['商机来源'],
                        'followTime' => $cell['下次跟进时间'],
                        'manager' => $manager['stid'] ?: self::$stid,
                        'collaborator' => implode(',', array_unique($collaborator)),
                        'text' => $cell['备注'],
                    ];
                    $annotation = [
                        'name' => L('opportunity.importData.name'),
                        'khid' => L('opportunity.importData.khid'),
                        'exSaleMoney' => L('opportunity.importData.exSaleMoney'),
                        'exSignDate' => L('opportunity.importData.exSignDate'),
                    ];
                    $rules = [
                        'name' => 'required',
                        'khid' => 'required',
                        'exSaleMoney' => 'required|numeric',
                        'exSignDate' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if (!empty($cell['负责人编号']) && !$manager['stid']) {
                        $text .= str_replace(['{{i}}'], [$row_list], L('opportunity.importData.stidEmpty'));
                    } elseif ($result === false) {
                        $text .= "\n".str_replace(['{{i}}'], [$row_list], L('opportunity.importData.row')) . $vt->getErrs()[0];
                    } else {
                        //查看范围
                        $field['see'] = implode(',', array_unique(array_merge(explode(',', $field['collaborator']), [$field['manager']])));
                        $warn = insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= "第【{$row_list}】行：导入成功<br>";
                        } else {
                            $text .= "第【{$row_list}】行：导入失败：编辑失败<br>";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = str_replace(['{{staffName}}','{{fileName}}'], [$this->control['name'],$_FILES['file']['name']], L('opportunity.importData.log')). '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = L('opportunity.exportData.power');
        } else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table . " as a join kehu as b on a.khid = b.khid",
                    'field' => 'a.*,b.companyName',
                    "where" => "a.id in ('".implode("','", $checkedId)."') order by a.time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $kehu = query('kehu',"khid = '$array[khid]'");
                $contacts = explode(',', $array['contacts']);
                $contactsName = '';
                foreach ($contacts as $id) {
                    if ($id =='frequent'){
                        $kehuStaff['name'] = $kehu['contactName'];
                    }else{
                        $kehuStaff = query('kehu_staff', "id = '$id'");
                    }
                    $contactsName .= $kehuStaff['name'] . ',';
                }
                $contactsName = rtrim($contactsName, ',');
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '商机标题'=>$array['name'],
                            '对应客户'=>$array['companyName'],
                            '关联联系人'=>$contactsName,
                            '关联产品'=>'',
                            '预计销售金额（元）'=>$array['exSaleMoney'],
                            '预计签单日期'=>$array['exSignDate'],
                            '销售阶段'=>$array['stage'],
                            '签单可能性'=>$array['possibility'],
                            '输单原因'=>$array['reason'],
                            '商机获取日期'=>$array['obtainDate'],
                            '商机来源'=>$array['source'],
                            '下次跟进时间'=>$array['followTime'],
                            '负责人'=>self::findStaff($array['manager']),
                            '协作人'=>clueClass::showMember($array['collaborator'], 2),
                            '备注'=>$array['text'],
                            '创建人'=> self::findStaff($array['stid']),
                            '更新时间'=>$array['updateTime'],
                            '创建时间'=>$array['time'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('opportunity.exportData.log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('opportunity.exportData.fileName').".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('opportunity.operate.del');
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('opportunity.operate.warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('opportunity.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('opportunity.delete.noChoice');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['manager'] != self::$stid) {
                    //返回
                    $warn = L('opportunity.delete.fail');
                } else {
                    $result = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                    foreach ($result['array'] as $file) {
                        fileDelete($file['src']);
                    }
                    //删除附件
                    delete(array("table" => "file", "where" => " targetId = '$id' "));
                    //删除跟进记录
                    delete(array("table" => "follow", "where" => " targetId = '$id' "));
                    //删除操作日志
                    delete(array("table" => "clue_log", "where" => " orderId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = L('opportunity.delete.success');
                    $x++;
                }
                $text .= str_replace(['{{id}}'], [$info['id']], L('opportunity.delete.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('opportunity.delete.log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('opportunity.delete.warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function logOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('opportunity.log.time') => text(array("name" => "recordDate", 'laydate' => ['type' => 'date', 'range' => '~'])).
                        hidden(array('name' => 'id', 'value' => $this->get('id'))),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 操作记录
     */
    public function log()
    {
        $html = $this->logOptions(false);
        //控件
        $button = "";
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    /**
     * 操作记录
     * @return bool|string
     */
    public function logSearch()
    {
        $id = $this->post('id');
        $where = " and orderId = '$id'";
        if ($this->post('recordDate')) {
            $timeArr = explode(' ~ ', $this->post('recordDate'));
            $where .= " and date(time) >='{$timeArr[0]}' and  date(time) <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        $page = $this->page([
            "table" => "clue_log",
            "where" => " {$where} ",
            "order" => $orderBy['orderBy']
        ]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
        $json['html'] = $page['hint'] . "<form name='topicForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 日志写入
     */
    public function logWrite($id, $type, $text = '')
    {
        $info = query(self::table, " id = '$id'");
        insert(array(
            'table' => 'clue_log',
            'field' => [
                'id' => self::getId(),
                'coid'=>self::$coid,
                'orderId' => $id,
                'classify' => '商机',
                'type' => $type,
                'text' => $text ?: str_replace(['{{staffName}}','{{type}}','{{name}}'], [$this->control['name'],$type,$info['name']], L('opportunity.logWrite.text')),
                'staffName' => $this->control['name'],
                'stid' => $this->control['stid'],
                'time' => $this->time
            ]
        ));
    }

    /*列表页-查询条件*/
    public function clientOptOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('opportunity.homeForm.name')   => text(array('name' => 'name')).
                        hidden(array("name" => "targetId","value" => $this->get('id'))),
                    L('opportunity.homeForm.stage') => select(array('name' => 'stage', 'option' => explode('，', para('stageOption')))),
                    L('opportunity.homeForm.possibility') => select(array('name' => 'possibility', 'option' => explode('，', para('possibilityOption')))),
                ],
                [
                    L('opportunity.detail.time') => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    L('opportunity.homeForm.manager') => selectMultiple(array('table' => 'staff', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'manager', 'class' => 'width200')),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 客户页卡商机
     * @return bool|string
     */
    public function clientOpt(): bool|string
    {
        $khid = $this->get('id');
        $html = $this->clientOptOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{khid:'" . $khid . "'})\" class='spanButton'>".L('opportunity.clientOptSearch.new')."</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('opportunity.clientOptSearch.del')."</span>\n";
        }
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    public function clientOptSearch(): bool|string
    {
        $khid = $this->post('targetId');
        //全等查询数组
        $equal = array(
            'possibility' => $this->post('possibility'),
            'stage' => $this->post('stage'),
        );
        $like = array(
            "name" => $this->post('name'),//标题
        );
        $and = " and khid = '".$khid."'";
        if ($this->post('time')) {
            $timeArr = explode(' ~ ', $this->post('time'));
            $and .= " and date(time) >='{$timeArr[0]}' and date(time) <='{$timeArr[1]}'";
        }
        //获取查询结果
        $where = search(array("=" => $equal, 'like' => $like)) . $and;
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        $page = $this->page(array("table" => self::table ,  "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array($this->checkAll("listForm", "listId"));
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => L('opportunity.clientOptSearch.edit'), "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
                "detail" => array("title" => L('opportunity.clientOptSearch.detail'), "click" => "newIframe('" . L('opportunity.clientOptSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $follow = query('follow', " targetId = '$array[id]' order by time desc");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "manager":
                        $row[] = self::findStaff($array['manager']);
                        break;
                    case "text":
                    case "time":
                        $row[] = $follow[$key];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'商机标题',
                    'aliasName'=>'商机标题',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'对应客户',
                    'aliasName'=>'对应客户',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'关联联系人',
                    'aliasName'=>'关联联系人（多个用英文逗号隔开）',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'预计销售金额',
                    'aliasName'=>'预计销售金额',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'预计签单日期',
                    'aliasName'=>'预计签单日期',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'销售阶段',
                    'aliasName'=>'销售阶段',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'签单可能性',
                    'aliasName'=>'签单可能性',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'输单原因',
                    'aliasName'=>'输单原因',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'商机获取日期',
                    'aliasName'=>'商机获取日期',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'商机来源',
                    'aliasName'=>'商机来源',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'下次跟进时间',
                    'aliasName'=>'下次跟进时间',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'负责人',
                    'aliasName'=>'负责人',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'负责人编号',
                    'aliasName'=>'负责人编号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'协作人',
                    'aliasName'=>'协作人',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'协作人编号',
                    'aliasName'=>'协作人编号(多个用英文逗号隔开)',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                    'isMust'=>false,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'商机标题',
                    'aliasName'=>'商机标题',
                ],
                [
                    'columnName'=>'对应客户',
                    'aliasName'=>'对应客户',
                ],
                [
                    'columnName'=>'关联联系人',
                    'aliasName'=>'关联联系人',
                ],
                [
                    'columnName'=>'关联产品',
                    'aliasName'=>'关联产品',
                ],
                [
                    'columnName'=>'预计销售金额',
                    'aliasName'=>'预计销售金额（元）',
                ],
                [
                    'columnName'=>'预计签单日期',
                    'aliasName'=>'预计签单日期',
                ],
                [
                    'columnName'=>'销售阶段',
                    'aliasName'=>'销售阶段',
                ],
                [
                    'columnName'=>'签单可能性',
                    'aliasName'=>'签单可能性',
                ],
                [
                    'columnName'=>'输单原因',
                    'aliasName'=>'输单原因',
                ],
                [
                    'columnName'=>'商机获取日期',
                    'aliasName'=>'商机获取日期',
                ],
                [
                    'columnName'=>'商机来源',
                    'aliasName'=>'商机来源',
                ],
                [
                    'columnName'=>'下次跟进时间',
                    'aliasName'=>'下次跟进时间',
                ],
                [
                    'columnName'=>'负责人',
                    'aliasName'=>'负责人',
                ],
                [
                    'columnName'=>'协作人',
                    'aliasName'=>'协作人',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
                [
                    'columnName'=>'创建人',
                    'aliasName'=>'创建人',
                ],
                [
                    'columnName'=>'更新时间',
                    'aliasName'=>'更新时间',
                ],
                [
                    'columnName'=>'创建时间',
                    'aliasName'=>'创建时间',
                ],
            ]
        };
    }
}
